<!-- 这是新闻资讯页面 -->
<template>
  <div id="news">
    <!-- 表单内容 -->
    <div class="search public">
      <myForm v-bind="formConfig" v-model:formData="formData">
        <template #header>
          <Title>
            <template #title>新闻资讯</template>
          </Title>
        </template>
        <template #footer>
          <div class="footer">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </template>
      </myForm>
    </div>
    <!-- 表格信息 -->
    <div class="public table">
      <myTable
        :tableData="tableData"
        v-model:pageList="pageList"
        v-bind="tableConfig"
      >
        <template #header>
          <Title>
            <template #title> 新闻资讯数据表 </template>
            <template #right>
              <el-button type="success" @click="handleAdd">新增文章</el-button>
            </template>
          </Title>
        </template>
        <template #cover="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
            fit="cover"
        /></template>
        <template #time="scope">
          {{ formatDate(scope.row.time) }}
        </template>
        <template #updateTime="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
        <template #isShow="scope">
          <el-switch
            v-model="scope.row.isShow"
            inline-prompt
            :active-icon="Check"
            :inactive-icon="Close"
            @click="handleChange(scope.row)"
          />
        </template>
        <template #operation="scope">
          <el-tooltip effect="dark" content="编辑文章" placement="top">
            <el-button
              type="primary"
              :icon="Edit"
              circle
              @click="hanldeRoutr(scope.row._id)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" content="删除文章" placement="top">
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleDelete(scope.row._id)"
            />
          </el-tooltip>
        </template>
        <template #author="scope">
          <template v-if="scope.row.author?.name">
            {{ scope.row.author?.name }}
          </template>
          <template v-else> 该用户已注销 </template>
        </template>
      </myTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

import myForm from '@/base-ui/form'
import myTable from '@/base-ui/table'
import { Title } from '@/components/admin/public'

import { formConfig, tableConfig } from '@/views/admin/config/news.config'

import { getEffectData } from '@/server/client/api_article'
import {
  deleteArticle,
  updateArticleIsShow,
  searchArticle
} from '@/server/serve/api_article'

import type { ArticleListDataTypes } from '@/server/client/api_article'

import formatDate from '@/utils/dayjs'

import { ElMessageBox, ElMessage } from 'element-plus'
import { Delete, Edit, Check, Close } from '@element-plus/icons-vue'

const router = useRouter()

// 表单数据
const newFormData: any = {}
for (const item of formConfig.formItems) {
  newFormData[`${item.field}`] = ''
}
const formData = ref(newFormData)

// 表格数据
const tableData = ref<any>()

// 分页数据
const pageList = ref({
  // 当前分页页数
  currentPage: 1,
  // 当前展示数据条数
  pageSize: 10,
  // 数据总数
  total: 0,
  pageSizes: [5, 10, 15, 20]
})

// 监听表格数据展示方式，是否为默认 搜索数据
const defaultDataShowType = ref<boolean>(true)

// 数据初始化
const dataInitialization = () => {
  // 默认数据
  if (defaultDataShowType.value) {
    getEffectData(
      0,
      pageList.value.pageSize,
      'true',
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    ).then(({ data: articleList }) => {
      tableData.value = articleList.data?.articleList
      pageList.value.total = articleList.data?.allNums!
    })
  }
  // 搜索数据
  else {
    searchArticle(
      0,
      formData.value.name,
      pageList.value.pageSize,
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    ).then(({ data: searchResult }) => {
      tableData.value = searchResult.data?.articleList
      pageList.value.total = searchResult.data?.allNums!
    })
  }
}

// 监听分页切换
watch(
  pageList,
  () => {
    dataInitialization()
  },
  { immediate: true }
)

// 切换是否展示
/**
 *
 * @param articleID 文章ID
 */
const handleChange = async (item: ArticleListDataTypes) => {
  const { _id, isShow } = item
  const { data: changeResult } = await updateArticleIsShow(_id)

  if (changeResult.code) {
    item.isShow = !isShow
    return ElMessage({
      type: 'warning',
      message: changeResult.mes
    })
  }
  ElMessage({
    type: 'success',
    message: changeResult.mes
  })
}

// 编辑文章
/**
 *
 * @param articleID 文章ID
 */
const hanldeRoutr = (articleID: string) => {
  router.push(`/admin/article/${articleID}`)
}

// 删除文章
const handleDelete = (articleID: string) => {
  ElMessageBox.confirm('确认删除该公益作用相关的文章吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data: deleteResult } = await deleteArticle(articleID)
      if (deleteResult.code)
        return ElMessage({
          type: 'warning',
          message: deleteResult.mes
        })
      dataInitialization()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      console.log()
    })
}

// 搜索文章
const handleSearch = async () => {
  defaultDataShowType.value = false
  dataInitialization()
}

// 新增文章
const handleAdd = () => {
  router.push('/admin/create')
}
</script>

<style scoped lang="less">
#news {
  .public {
    padding: 0px 20px 20px;
    background-color: #fff;
    border-radius: 16px;
    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
  .table {
    padding: 20px;
    margin-top: 20px;
  }
}
</style>
